package com.edgclub.edg.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;

import com.edgclub.edg.Constant;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

import me.nereo.multi_image_selector.bean.Image;


/**
 * 多图选择
 * Created by Nereo on 2015/4/7.
 * Updated by nereo on 2016/register_1/19.
 */
public class MultiImageSelectorActivity extends FragmentActivity implements MultiImageSelectorFragment.Callback{

    /** 最大图片选择次数，int类型，默认9 */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /** 图片选择模式，默认多选 */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /** 是否显示相机，默认显示 */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    /** 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合  */
    public static final String EXTRA_RESULT = "select_result";
    /** 默认选择集 */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";

    /** 单选 */
    public static final int MODE_SINGLE = 0;
    /** 多选 */
    public static final int MODE_MULTI = 1;

    private ArrayList<Image> resultList = new ArrayList<>();
    private Button mSubmitButton;
    private int mDefaultCount;

    /**
     *选择图片的类型 1=头像
     */
    private int selectType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(me.nereo.multi_image_selector.R.layout.activity_default);

        final Intent intent = getIntent();
        selectType=intent.getIntExtra("selectType",0);
        mDefaultCount = intent.getIntExtra(EXTRA_SELECT_COUNT, 9);
        int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
        boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        if(mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultList = (ArrayList<Image>) intent.getSerializableExtra(EXTRA_DEFAULT_SELECTED_LIST);
        }

        Bundle bundle = new Bundle();
        bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
        bundle.putInt(MultiImageSelectorFragment.EXTRA_SELECT_MODE, mode);
        bundle.putBoolean(MultiImageSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
        bundle.putSerializable(MultiImageSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, (Serializable)resultList);
        bundle.putInt("selectType", selectType);
        getSupportFragmentManager().beginTransaction()
                .add(me.nereo.multi_image_selector.R.id.image_grid, Fragment.instantiate(this, MultiImageSelectorFragment.class.getName(), bundle))
                .commit();

        // 返回按钮
        findViewById(me.nereo.multi_image_selector.R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });

        // 完成按钮
        mSubmitButton = (Button) findViewById(me.nereo.multi_image_selector.R.id.commit);
        if(resultList == null || resultList.size()<=0){
            mSubmitButton.setText(me.nereo.multi_image_selector.R.string.action_done);
            mSubmitButton.setEnabled(false);
        }else{
            updateDoneText();
            mSubmitButton.setEnabled(true);
        }
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (resultList != null && resultList.size() > 0) {
                    // 返回已选择的图片数据
                    Intent data = new Intent();
                    data.putExtra(EXTRA_RESULT, (Serializable) resultList);
                    setResult(RESULT_OK, data);
                    finish();
                }
            }
        });
        if(selectType!=0){
            mSubmitButton.setVisibility(View.GONE);
        }else{
            mSubmitButton.setVisibility(View.VISIBLE);
        }
    }

    private void updateDoneText(){
        mSubmitButton.setText(String.format("%s(%d/%d)",
                getString(me.nereo.multi_image_selector.R.string.action_done), resultList.size(), mDefaultCount));
    }

    @Override
    public void onSingleImageSelected(Image image) {
        if (selectType == 1||selectType == 2) {
            Intent intent1=new Intent(MultiImageSelectorActivity.this,CutPhotoActivity.class);
            intent1.putExtra(EXTRA_RESULT,image);
            intent1.putExtra("selectType",selectType);
            startActivityForResult(intent1, Constant.IMAGE_RESULT);
        } else if(selectType==3){
            Intent intent=new Intent(MultiImageSelectorActivity.this,ImageSendActivity.class);
                intent.putExtra("image", image);
            startActivityForResult(intent, Constant.IMAGE_RESULT);
        }else{
            Intent data = new Intent();
            resultList.add(image);
            data.putExtra(EXTRA_RESULT, (Serializable) resultList);
            setResult(RESULT_OK, data);
            finish();
        }

    }

    @Override
    public void onImageSelected(Image image) {
        if(!resultList.contains(image)) {
            resultList.add(image);
        }
        // 有图片之后，改变按钮状态
        if(resultList.size() > 0){
            updateDoneText();
            if(!mSubmitButton.isEnabled()){
                mSubmitButton.setEnabled(true);
            }
        }
    }

    @Override
    public void onImageUnselected(Image image) {
        if(resultList.contains(image)){
            resultList.remove(image);
        }
        updateDoneText();
        // 当为选择图片时候的状态
        if(resultList.size() == 0){
            mSubmitButton.setText(me.nereo.multi_image_selector.R.string.action_done);
            mSubmitButton.setEnabled(false);
        }
    }

    @Override
    public void onCameraShot(File imageFile) {
        if(imageFile != null) {

            // notify system
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));

            if (selectType == 1||selectType == 2) {
                Intent intent1=new Intent(MultiImageSelectorActivity.this,CutPhotoActivity.class);
                Image image = new Image(imageFile.getAbsolutePath(),imageFile.getName(),System.currentTimeMillis(),false);
                intent1.putExtra(EXTRA_RESULT,image);
                intent1.putExtra("selectType",selectType);
                startActivityForResult(intent1, Constant.IMAGE_RESULT);
            } else {
                Intent data = new Intent();
                Image image = new Image(imageFile.getAbsolutePath(),imageFile.getName(),System.currentTimeMillis(),false);
                resultList.add(image);
                data.putExtra(EXTRA_RESULT, resultList);
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }

    @Override
    public void onSelectList(ArrayList<Image> images) {
        resultList = (ArrayList<Image>) images.clone();
        // 有图片之后，改变按钮状态
        if(resultList.size() > 0){
            if(!mSubmitButton.isEnabled()){
                mSubmitButton.setEnabled(true);
            }
        }else{
            mSubmitButton.setText(me.nereo.multi_image_selector.R.string.action_done);
            mSubmitButton.setEnabled(false);
        }
        updateDoneText();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constant.IMAGE_RESULT) {
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }
}
